package com.ybjzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ybjzo2o.common.expcetions.CommonException;
import com.ybjzo2o.common.expcetions.ForbiddenOperationException;
import com.ybjzo2o.common.model.PageResult;
import com.ybjzo2o.foundations.constants.RedisConstants;
import com.ybjzo2o.foundations.enums.FoundationStatusEnum;
import com.ybjzo2o.foundations.mapper.ServeMapper;
import com.ybjzo2o.foundations.mapper.ServeItemMapper;
import com.ybjzo2o.foundations.mapper.RegionMapper;
import com.ybjzo2o.foundations.model.domain.Region;
import com.ybjzo2o.foundations.model.domain.Serve;
import com.ybjzo2o.foundations.model.domain.ServeItem;
import com.ybjzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.ybjzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.ybjzo2o.foundations.model.dto.response.ServeResDTO;
import com.ybjzo2o.foundations.service.IServeService;
import com.ybjzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * * <p>
 * * 服务实现类
 * * </p>
 * *
 * * @author itfhy
 * */

@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {
    @Autowired
    private ServeItemMapper serveItemMapper;
    @Autowired
    private RegionMapper regionMapper;
    /**
     * 分页查询
     *
     * @param servePageQueryReqDTO 查询条件
     * @return 分页结果
     */
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        //通过baseMapper调用queryServeListByRegionId方法
        //调用mapper查询数据，这里由于继承了ServiceImpl<ServeMapper, Serve>，使用baseMapper相当于使用ServeMapper
        PageResult<ServeResDTO> serveResDTOPageResult = PageHelperUtils
                .selectPage(servePageQueryReqDTO, () ->
                        baseMapper.queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));
        return serveResDTOPageResult;
    }
    @Override
    @Transactional
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        for (ServeUpsertReqDTO serveUpsertReqDTO : serveUpsertReqDTOList) {
//1.校验服务项是否为启用状态，不是启用状态不能新增
            ServeItem serveItem =
                    serveItemMapper.selectById(serveUpsertReqDTO.getServeItemId());
//如果服务项信息不存在或未启用
            if(ObjectUtil.isNull(serveItem)
                    ||
                    serveItem.getActiveStatus()!= FoundationStatusEnum.ENABLE.getStatus()){
                throw new ForbiddenOperationException("该服务未启用无法添加到区域下使用");
            }
//2.校验是否重复新增
            Integer count = lambdaQuery()
                    .eq(Serve::getRegionId, serveUpsertReqDTO.getRegionId())
                    .eq(Serve::getServeItemId, serveUpsertReqDTO.getServeItemId())
                    .count();
            if(count>0){
                throw new ForbiddenOperationException(serveItem.getName()+"服务已存 在");
            }
//3.新增服务
            Serve serve = BeanUtil.toBean(serveUpsertReqDTO, Serve.class);
            Region region =
                    regionMapper.selectById(serveUpsertReqDTO.getRegionId());
            serve.setCityCode(region.getCityCode());
            baseMapper.insert(serve);
        }
    }
    @Override
    @Transactional
    public Serve update(Long id, BigDecimal price) {
//1.更新服务价格
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getPrice, price)
                .update();
        if(!update){
            throw new CommonException("修改服务价格失败");
        }
        return baseMapper.selectById(id);
    }
    @Override
    @Transactional
    @CachePut(value = RedisConstants.CacheName.SERVE, key = "#id",
            cacheManager = RedisConstants.CacheManager.ONE_DAY)
    public Serve onSale(Long id){
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
//上架状态
        Integer saleStatus = serve.getSaleStatus();
//草稿或下架状态方可上架
        if (!(saleStatus==FoundationStatusEnum.INIT.getStatus()
                || saleStatus==FoundationStatusEnum.DISABLE.getStatus())) {
            throw new ForbiddenOperationException("草稿或下架状态方可上架");
        }
//服务项id
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if(ObjectUtil.isNull(serveItem)){
            throw new ForbiddenOperationException("所属服务项不存在");
        }
//服务项的启用状态
        Integer activeStatus = serveItem.getActiveStatus();
//服务项为启用状态方可上架
        if (!(FoundationStatusEnum.ENABLE.getStatus()==activeStatus)) {
            throw new ForbiddenOperationException("服务项为启用状态方可上架");
        }
//更新上架状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if(!update){
            throw new CommonException("启动服务失败");
        }
        return baseMapper.selectById(id);
    }



    //下架
    @Override
    @Transactional
    @CacheEvict(value = RedisConstants.CacheName.SERVE, key = "#id")
    public Serve offSale(Long id) {
        //1.校验服务是否存在
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //2.校验服务状态是否为上架状态
        if (serve.getSaleStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("服务状态不为上架状态,无法下架");
        }
        //3.更新服务状态为下架
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if (!update) {
            throw new CommonException("服务下架失败");
        }
        return baseMapper.selectById(id);
    }

    //删除服务
    @Override
    @Transactional
    public void delete(Long id) {
        //1.校验服务是否存在
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //2.校验服务状态是否为草稿状态
        if(serve.getSaleStatus()!= FoundationStatusEnum.INIT.getStatus()){
            throw new ForbiddenOperationException("服务状态不为草稿状态,无法删除");
        }
        //3.删除服务
        baseMapper.deleteById(id);
    }



    /**
     * 服务设置热门/取消
     *
     * @param id   服务id
     * @param flag 是否为热门，0：非热门，1：热门
     */
    @Override
    @Transactional
    public void changeHotStatus(Long id, Integer flag) {
        //1.设置热门
        LambdaUpdateWrapper<Serve> updateWrapper = Wrappers.<Serve>lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, flag)
                .set(Serve::getHotTimeStamp, System.currentTimeMillis());
        super.update(updateWrapper);
    }
    @Override
   /* public Serve queryServeByIdCache(Long id) {
        return getById(id);
    }*/
    // @Cacheable(value = "JZ_CACHE:SERVE_RECORD",key = "#id")
    @Cacheable(value = RedisConstants.CacheName.SERVE,key = "#id")//在对应的缓存上加注解使用@Cacheable
    public Serve queryServeByIdCache(Long id) {
        return getById(id);
    }



}